package table.source;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import table.DataTable;
import table.inter.TableSource;

public class TableSourceSpringXml implements TableSource {
	private String sourceName;
	private String sourcefilepath;
	private List<DataTable> tableList;

	public void setSourceName(String sourceName) {
		this.sourceName = sourceName;
	}
	public String getSourceName() {
		return sourceName;
	}
	
	public void setSourcefilepath(String sourcefilepath) {
		this.sourcefilepath = sourcefilepath;
		this.setTableListByPath();
	}
	public String getSourcefilepath() {
		return sourcefilepath;
	}
	private boolean setTableListByPath(){
		
		if(null == this.tableList){
			this.tableList = new ArrayList<DataTable>();
		}
		try{
			this.tableList.clear();
			ApplicationContext context = new ClassPathXmlApplicationContext(this.getSourcefilepath());
			Map<?, ?> tablesmap = context.getBeansOfType(DataTable.class);
			for(Object bean : tablesmap.values()) {
				DataTable table = (DataTable)bean;
				if(table != null){
					this.tableList.add(table);
				}
			}
			return true;
		}catch(Exception e){
		}
		return false;
	}
	public List<DataTable> getTableList() {
		if(null == this.tableList){
			this.setTableListByPath();
		}
		return this.tableList;
	}
	
	public DataTable get(int i) {
		try{
			if(null == this.tableList){
				this.setTableListByPath();
			}
			return this.getTableList().get(i);
		} catch(Exception e){
			
		}
		return null;
	}
	
}
